//
//  ProblemOffer29.swift
//  TestProject
//
//  Created by 武侠 on 2021/7/15.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit


/*
 剑指 Offer 29. 顺时针打印矩阵 ✅
 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。

 示例 1：
     输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     输出：[1,2,3,6,9,8,7,4,5]
 示例 2：
     输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 限制：
 0 <= matrix.length <= 100
 0 <= matrix[i].length <= 100
 */
@objcMembers class ProblemOffer29: NSObject {
    func solution() {
        print(spiralOrder([]))
        print(spiralOrder([[1]]))
        print(spiralOrder([[1], [2]]))
        print(spiralOrder([[1,2,3],[4,5,6],[7,8,9]]))
        print(spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]))
    }
    
    
    /*
     1 2 3 4 5 6 7 8
     1 2 3 4 5 6 7 8
     1 2 3 4 5 6 7 8
     1 2 3 4 5 6 7 8
     1 2 3 4 5 6 7 8
     [1,2,3],
     [4,5,6],
     [7,8,9]
     */
    func spiralOrder(_ matrix: [[Int]]) -> [Int] {
        if matrix.count == 0 {
            return []
        }
        let statue = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        var si = 0
        // 四个结束点
        var ends = [(0, matrix[0].count-1), (matrix.count-1, matrix[0].count-1), (matrix.count-1, 0), (1, 0)]
        let endStatue = [(1, -1), (-1, -1), (-1, 1), (1, 1)]
        
        var list:[Int] = Array(repeating: 0, count: matrix.count * matrix[0].count)
        var x = 0, y = -1
        var li = 0
        
        while li < list.count {
            x += statue[si].0
            y += statue[si].1

            list[li] = matrix[x][y]
            li += 1
            
            if x == ends[si].0, y == ends[si].1 {
                ends[si].0 += endStatue[si].0
                ends[si].1 += endStatue[si].1
                si = (si + 1) % statue.count
            }
        }
        
        return list
    }
}
